from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, reverse
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
# Create your views here.


def captcha():
    # 创建验证码
    # 会在数据库中生成验证码信息
    # hashkey: 通过hashkey获取数据库中图片验证码的正确值
    # image_url: 图片验证码地址
    hashkey = CaptchaStore.generate_key()  # 验证码hashkey值
    image_url = captcha_image_url(hashkey)  # 验证码图片地址
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha


@csrf_exempt
def refresh_captcha(request):
    # 刷新验证码
    return HttpResponse(json.dumps(captcha()), content_type='application/json')


def jarge_captcha(captcha_str, captcha_hashkey):
    """
    验证用户输入的验证码信息
    :param captcha_str: 用户输入的验证码字符串
    :param captcha_hashkey: 对应验证码的hashkey值
    :return: True/False
    """
    if captcha_str and captcha_hashkey:
        try:
            # 根据hashkey获取数据库中验证码的真实值
            get_captcha = CaptchaStore.objects.get(hashkey=captcha_hashkey)
            if get_captcha.response == captcha_str.lower():
                return True
        except:
            return False
    else:
        return False


def get_user_ip(request):
    # 获取用户IP地址
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        user_ip = request.META.get('HTTP_X_FORWARDED_FOR', 'unknow')
    else:
        user_ip = request.META.get('REMOTE_ADDR', 'unknow')
    return user_ip


@csrf_exempt
def sign(request):
    """
    用户登录验证
    :param request:
    :return:
    1. 如果用户已经登录则重定向到已登录主界面
    2. GET请求，返回用户登录界面信息，和验证码
    3. POST请求，处理用户提交的登录信息，校验用户的合法性
    """
    # 如果用户已经登录，重定向到用户主界面
    if request.user.is_authenticated:
        return redirect(reverse('pages:homepage'))
    # 返回渲染后的登录界面模板
    if request.method == 'GET':
        hashkey = CaptchaStore.generate_key()
        image_url = captcha_image_url(hashkey)
        captcha = {'hashkey': hashkey, 'image_url': image_url}
        return render(request, 'login.html', {'captcha': captcha})
    # 处理用户提交的登录信息
    elif request.method == 'POST':
        result = {'code': 0, 'message': ''}

        sign_datas_str = request.POST.get('sign_datas', '')
        hashkey = request.POST.get('hashkey', '')
        if sign_datas_str:
            #    sign_info_dic = {
            #        "username": username,
            #        "password": password,
            #       "login_input_captcha": login_input_captcha,
            #   }
            sign_info_dic = {item['name']: item['value'] for item in json.loads(sign_datas_str)}

            if jarge_captcha(str(sign_info_dic['login_input_captcha']).replace(' ', ''), hashkey):
                user = authenticate(request, username=sign_info_dic['username'], password=sign_info_dic['password'])
                if user is not None:
                    login(request, user)
                    user.profile.last_login_ip = get_user_ip(request)
                    user.save()
                    if not sign_info_dic.get('keep_sign', ''):
                        # 设置session失效时间
                        # 如果是一个整数，则在用户不活动的n秒后过期
                        # 如果是0则关闭浏览器后过期
                        # 如果是None则永不过期
                        request.session.set_expiry(0)
                    result['code'] = 1
                    result['message'] = '登陆成功！'
                else:
                    result['code'] = -1
                    result['message'] = '登录失败:用户名或密码错误！'
            else:
                result['code'] = -2
                result['message'] = '验证码错误！'
        else:
            result['code'] = -3
            result['message'] = '登录失败！'
        return HttpResponse(json.dumps(result))
    else:
        raise Exception('unknow http request')


@csrf_exempt
def register(request):
    """
    用户注册处理函数
    :param request:
    :return:
    用户注册成功后跳转至登录界面
    """
    result = {'code': '-4', 'message': '注册失败'}

    if request.method == 'POST':
        register_datas_str = request.POST.get('register_datas', '')
        hashkey = request.POST.get('hashkey', '')
        if register_datas_str:
            # register_info_dic = {
            #     "username": username,
            #     "password": password,
            #     "re_password": re_password,
            #     "reg_input_captcha": reg_input_captcha,
            #
            # }
            register_info_dic = {item['name']: item['value'] for item in json.loads(register_datas_str)}
            if jarge_captcha(str(register_info_dic['reg_input_captcha']).replace(' ', ''), hashkey):
                if register_info_dic['username'] and register_info_dic['password'] and register_info_dic['password'] == register_info_dic['re_password']:
                    try:
                        User.objects.create_user(username=register_info_dic['username'], password=register_info_dic['password'])
                    except Exception as ex:
                        print('==============================')
                        print(ex)
                        result['code'] = '-1'
                        result['message'] = '用户名重复！'
                    else:
                        result['code'] = '1'
                        result['message'] = '注册成功！'
                else:
                    result['code'] = '-2'
                    result['message'] = '注册失败！'
            else:
                result['code'] = '-3'
                result['message'] = '验证码错误!'
        else:
            result['code'] = '-4'
            result['message'] = '注册失败！'
        return HttpResponse(json.dumps(result))
    else:
        return HttpResponse(json.dumps(result))


@csrf_exempt
def exit(request):
    logout(request)
    return HttpResponseRedirect(reverse('login:sign'))


def protocol(request):
    return HttpResponse('<h1>协议内容！</h1>')



